package com.cl.db.optimisticlock.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.db.optimisticlock.aspect.OptimisticLockException;
import com.cl.db.optimisticlock.aspect.OptimisticLockReTry;
import com.cl.db.optimisticlock.mapper.OptimisticLockMapper;
import com.cl.db.optimisticlock.domain.OptimisticLock;
import com.cl.db.optimisticlock.service.IOptimisticLockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Small
 * @since 2020-05-25
 */
@Slf4j
@Service
public class OptimisticLockServiceImpl extends ServiceImpl<OptimisticLockMapper, OptimisticLock> implements IOptimisticLockService {

    /**
     * 方法描述: 更新账户金额
     * @Author Small
     * @param id      id
     * @param money   金额
     * @Date 2020/5/25 18:29

     */
    @Transactional(rollbackFor = Exception.class)
    @OptimisticLockReTry
    @Override
    public void updateMoney(long id, int money) {
        OptimisticLock byId = getById(id);
        byId.setMoney(byId.getMoney() + money);
        Integer version = byId.getVersion();
        int newVersion = version + 1;
//        byId.setVersion(version + 1);
        boolean b = updateById(byId);
        System.out.println("执行结果：" + b);
        if (!b) {
            log.info("更新失败{},{},version{}-{}", id, money, version, newVersion);
            throw new OptimisticLockException("更新失败");
        }
    }
}
